#include "memory_share.h"



MemoryShare::MemoryShare
(const std::string& name_, int capacity_, int timeout_wait_):
   name(name_),
   capacity(capacity_),
   p_mem(nullptr),
   is_init(false),
   timeout_wait(timeout_wait_)
{
    std::cout << "shared memory name: " << name << ", capacity: " << capacity_ << std::endl;
}

MemoryShare::~MemoryShare()
{
    exit();
    std::cout << "shared memory name: " << name << ", exit... ";
}

LPCWSTR MemoryShare::string2LPCWSTR(std::string str)
{
    size_t size = str.length();
    wchar_t *buffer = new wchar_t[size + 1];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), size, buffer, size * sizeof(wchar_t));
    buffer[size] = 0;
    return buffer;
}

bool MemoryShare::init()
{

    h_mapfile = CreateFileMapping(INVALID_HANDLE_VALUE,
        NULL,
        PAGE_READWRITE,
        0,
        capacity,
        MemoryShare::string2LPCWSTR(name));

    if (h_mapfile == nullptr)
    {
        std::cout << "Could not create file mapping object " << GetLastError() << std::endl;
        return false;
    }
    p_mem = (char*)MapViewOfFile(h_mapfile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        capacity);

    if (p_mem == nullptr)
    {
        std::cout << "Could not map view of file " << GetLastError() << std::endl;
        CloseHandle(h_mapfile);
        return false;
    }

    p_mem[0] = MemAvaliable;
    is_init = true;
    return true;
}

void MemoryShare::exit()
{
    if(!is_init) return;
    is_init = false;
    if(p_mem != nullptr)
    {
        UnmapViewOfFile(p_mem);
        p_mem = nullptr;
    }

    if(h_mapfile != nullptr)
    {
        CloseHandle(h_mapfile);
        h_mapfile = nullptr;
    }
}


